package com.docker.apps.afterservice.ui;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.Observable;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.dcbfhd.utilcode.utils.FragmentUtils;
import com.dcbfhd.utilcode.utils.KeyboardUtils;
import com.dcbfhd.utilcode.utils.LogUtils;
import com.dcbfhd.utilcode.utils.ToastUtils;
import com.docker.apps.R;
import com.docker.apps.afterservice.vm.AfterServiceViewModel;
import com.docker.apps.databinding.ProAfterServiceApplyActivityBinding;
import com.docker.apps.order.vo.AddressVo;
import com.docker.apps.order.vo.AfterServiceVo;
import com.docker.cirlev2.ui.common.CircleSourceUpFragment;
import com.docker.cirlev2.vo.param.SourceUpParam;
import com.docker.common.common.router.AppRouter;
import com.docker.common.common.ui.base.NitCommonActivity;
import com.docker.common.common.utils.cache.CacheUtils;
import com.docker.common.common.utils.rxbus.RxBus;
import com.docker.common.common.utils.rxbus.RxEvent;
import com.docker.common.common.vo.UserInfoVo;
import com.docker.common.common.vo.entity.ReasonEntity;
import com.docker.common.common.widget.XPopup.BottomPopup;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.XPopupCallback;

import java.util.HashMap;
import java.util.List;

/**
 * kxf -> 2020-02-18
 * 申请售后详情页面
 * apply_return_address
 **/
@Route(path = AppRouter.ORDER_AFTER_APPLY)
public class ApplyAfterServiceActivity extends NitCommonActivity<AfterServiceViewModel, ProAfterServiceApplyActivityBinding> {
    int returnNum, tempNum;
    private SourceUpParam mSourceUpParam;
    private CircleSourceUpFragment sourceUpFragment;
    boolean isReturn, isFirst;
    String orderId;
    AfterServiceVo.AfterServiceGood goodsInfo;
    String returnId;

    public int choose = 1;

    @Override
    public void initView() {

        mBinding.proEventDesc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mBinding.tvTextContent.setText(mBinding.proEventDesc.getText().toString().length() + "/500");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        isReturn = getIntent().getBooleanExtra("isReturn", false);
        isFirst = getIntent().getBooleanExtra("isFirst", true);
        orderId = getIntent().getStringExtra("orderid");
        returnId = getIntent().getStringExtra("returnId");
        goodsInfo = (AfterServiceVo.AfterServiceGood) getIntent().getSerializableExtra("goodsInfo");
        LogUtils.e(JSON.toJSON(goodsInfo));

        if (isReturn) {
            mToolbar.setTitle("退货");
        } else {
            mToolbar.setTitle("换货");
        }
        mBinding.setGoodInfo(goodsInfo);
        mBinding.setIsReturn(isReturn);
        reasonEntityList = CacheUtils.getReason();
        mBinding.applySubmit.setOnClickListener(v -> {
            if (sourceUpFragment.selectList != null && sourceUpFragment.selectList.size() > 0) {
                sourceUpFragment.processUpload();
            } else {
                realPublish();
            }
        });
        mSourceUpParam = new SourceUpParam(SourceUpParam.SOURCE_TYPE_AUTO, 9);
        sourceUpFragment = CircleSourceUpFragment.newInstance(mSourceUpParam);
        FragmentUtils.add(getSupportFragmentManager(), sourceUpFragment, com.docker.cirlev2.R.id.souce_up_frame);
        mSourceUpParam.status.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                // 根据状态回调 来判断是否能发布了
                switch (mSourceUpParam.status.get()) {
                    case 2:
                        realPublish();
                    case 3:
                        hidWaitDialog();
//                        ToastUtils.showShort("上传资源失败请重试！");
                        break;
                }
            }
        });
        mBinding.orderXiugai2.setOnClickListener(v -> {
            choose = 2;
            ARouter.getInstance().build(AppRouter.ORDER_ADDRESS_MANAGER).withString("type", "2").navigation(ApplyAfterServiceActivity.this, 10011);
        });
        mBinding.contactServiceName.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(mBinding.contactServiceName);
            if (basePopupView != null) {
                basePopupView.show();
            } else {
                String egid = "3586";
                if (isReturn) {
                    egid = "3587";
                }
                mViewModel.refundReason(egid);
            }
        });
        if (TextUtils.isEmpty(goodsInfo.goodsNum)) {
            returnNum = 0;
        } else {
            returnNum = Integer.parseInt(goodsInfo.goodsNum);
        }
        tempNum = returnNum;
        mBinding.tvAdd.setOnClickListener(v -> {
            if (tempNum >= returnNum)
                return;
            tempNum++;
            mBinding.tvNum.setText(String.valueOf(tempNum));
        });
        mBinding.tvReduce.setOnClickListener(v -> {
            if (tempNum == 1) return;
            tempNum--;
            mBinding.tvNum.setText(String.valueOf(tempNum));
        });
    }

    @Override
    public void initObserver() {
        mViewModel.mServerLiveData.observe(this, o -> {
            RxBus.getDefault().post(new RxEvent<>("updateAfterService", 1));
            ToastUtils.showShort("提交成功");
            finish();
        });

        mViewModel.mRefund_reason.observe(this, reasonEntities -> {
            reasonEntityList = reasonEntities;
            initPop();
        });

        String egid = "3587";
        if (isReturn) {
            egid = "3586";
        }
        mViewModel.refundReason(egid);
    }

    @Override
    public void initRouter() {
        ARouter.getInstance().inject(this);
    }

    private void realPublish() {
        UserInfoVo userInfoVo = CacheUtils.getUser();
        HashMap<String, String> params = new HashMap<>();

        if (!TextUtils.isEmpty(returnId)) {
            params.put("returnId", returnId);
        }
        if (!isReturn) {
            if (TextUtils.isEmpty(mBinding.proEventDesc.getText().toString())) {
                ToastUtils.showLong("请输入换货原因");
                return;
            }

            if ("-1".equals(reasonId)) {
                ToastUtils.showLong("请选择换货原因");
                return;
            }
            if (addressVo == null) {
                ToastUtils.showLong("请选择收货地址");
                return;
            }

            if (TextUtils.isEmpty(mBinding.applyT3.getText().toString())) {
                ToastUtils.showLong("请输入换货地址");
                return;
            }

            params.put("SellersAddress", mBinding.applyT3.getText().toString());
            params.put("addressid", addressVo.getId());
            params.put("refund_content", mBinding.proEventDesc.getText().toString());
            if (mSourceUpParam.imgList.size() > 0) {
                for (int i = 0; i < mSourceUpParam.imgList.size(); i++) {
                    params.put("refund_image[" + i + "][t]", "1");
                    params.put("refund_image[" + i + "][url]", mSourceUpParam.imgList.get(i));
                    params.put("refund_image[" + i + "][img]", mSourceUpParam.imgList.get(i));
                    params.put("refund_image[" + i + "][sort]", i + 1 + "");
                }
            }
        } else {
            if ("-1".equals(reasonId)) {
                ToastUtils.showLong("请选择退货原因");
                return;
            }
            if (TextUtils.isEmpty(mBinding.applyReturnAddress.getText().toString())) {
                ToastUtils.showLong("请输入退货地址");
                return;
            }
            params.put("SellersAddress", mBinding.applyReturnAddress.getText().toString());
        }

        params.put("memberid", userInfoVo.uid);
        params.put("uuid", userInfoVo.uuid);
        params.put("goodsid", goodsInfo.goodsid);
        params.put("orderid", orderId);
        params.put("goodsNum", String.valueOf(tempNum));
        params.put("type", isReturn ? "2" : "1");
        params.put("reason_id", reasonId);
        mViewModel.returnGoods(params);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.pro_after_service_apply_activity;
    }

    @Override
    public AfterServiceViewModel getmViewModel() {
        return ViewModelProviders.of(this, factory).get(AfterServiceViewModel.class);
    }

    AddressVo addressVo;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 10011) {
                addressVo = (AddressVo) data.getSerializableExtra("AddressVo");
                mBinding.applyT5.setText(addressVo.getName() + "   " + addressVo.getPhone());
                mBinding.applyT6.setText(addressVo.getAddress());

            } else {
                sourceUpFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }


    List<ReasonEntity> reasonEntityList;

    BasePopupView basePopupView;

    private String reasonId = "-1";

    private void initPop() {
        BottomPopup bottomPopup = new BottomPopup(this, "reason_style");
        basePopupView = new XPopup.Builder(this).setPopupCallback(new XPopupCallback() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onCreated() {
                ImageView iv_close = bottomPopup.findViewById(com.docker.common.R.id.iv_close);
                iv_close.setOnClickListener(v -> {
                    basePopupView.dismiss();

                });
                RadioGroup radioGroup = bottomPopup.findViewById(R.id.reason_r1);
                radioGroup.removeAllViews();
                for (int i = 0; i < reasonEntityList.size(); i++) {
                    RadioButton radioButton = new RadioButton(radioGroup.getContext());
                    radioButton.setText(reasonEntityList.get(i).getContent());
                    radioButton.setId(i);
                    radioButton.setCompoundDrawablePadding(10);
                    radioButton.setPadding(6, 6, 6, 6);
                    radioButton.setPaddingRelative(10, 10, 10, 10);
                    radioButton.setButtonDrawable(R.drawable.checkstate);
                    radioButton.setTextSize(14);
                    radioButton.setTextColor(Color.parseColor("#ff222222"));
                    RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(8, 8, 8, 8);
                    radioGroup.addView(radioButton, layoutParams);
                }

                bottomPopup.findViewById(R.id.reason_b1).setOnClickListener(v -> {
                    int dd = radioGroup.getCheckedRadioButtonId();
                    if (dd == -1) {
                        ToastUtils.showLong("请选择");
                        return;
                    }
                    Log.d("sss", "onCreated: =============" + dd);
//                    dd = dd - 1;
                    reasonId = reasonEntityList.get(dd).getId();
                    mBinding.contactServiceName.setText(reasonEntityList.get(dd).getContent());// = String.valueOf(radioGroup.getCheckedRadioButtonId());
                    bottomPopup.dismiss();
                });

            }

            @Override
            public void beforeShow() {

            }

            @Override
            public void onShow() {

            }

            @Override
            public void onDismiss() {

            }

            @Override
            public boolean onBackPressed() {
                return false;
            }
        }).asCustom(bottomPopup);

    }

}